﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.BLL.Ali;
using CRM.UTIL;
using CRM.WEB.CommonClass;
using System.Text;

namespace CRM.WEB.Ali
{
    public partial class ValidateOrder : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpLoad_Click(object sender, EventArgs e)
        {
            if (fileControl.HasFile)
            {
                try
                {
                    string folder = string.Empty;
                    string dirPath = CommonClass.Common.GetUpLoadDirPath(Server, out folder);


                    string fileName = fileControl.FileName;
                    string strFileExt = fileName.Substring(fileName.LastIndexOf(".", StringComparison.Ordinal) + 1);

                    fileName = CommonClass.Common.GetNewFileName(dirPath, fileName);
                    if (!string.IsNullOrEmpty(strFileExt) && (strFileExt.ToLower() == "xls") ||
                        strFileExt.ToLower() == "xlsx")
                    {
                        //upload to server
                        string serverName = Server.MapPath(folder).Trim('\\') + "\\" + fileName;
                        fileControl.PostedFile.SaveAs(serverName);


                        var dt = ExcelHelper.ExcelToTable(serverName);

                        const string colOrderID = "order_id";


                        if (!dt.Columns.Contains(colOrderID))
                        {
                            ShowAlert("文件列不合法！不包含列：order_id");
                            return;
                        }

                        var sbFail = new StringBuilder();
                        var notexistSb = new StringBuilder();

                        var succCount = 0;
                        var addSuccessCount = 0;
                        var failCount = 0;
                        var notexistCount = 0;

                        var serv = new Ali_OrdersB();
                        var aliApiServ = new RunAliAPI();
                        var supplierId = ConfigurationManager.AppSettings["SupplierId"];
                        for (var i = 0; i < dt.Rows.Count; i++)
                        {
                            try
                            {
                                var dr = dt.Rows[i];

                                if (string.IsNullOrEmpty(dr[colOrderID].ToString().Trim()))
                                {
                                    failCount++;
                                    sbFail.Append("第" + (i + 1) + "行订单号为空！\r\n");
                                    continue;
                                }

                                //根据订单号判断是否存在
                                var stu = new MODEL.Ali.GetAli_Orders();
                                stu.ORDERIDVALUE = dr[colOrderID];
                                var oDt = serv.GetAli_Orders(ref stu);

                                if (oDt == null || oDt.Rows.Count <= 0)
                                {
                                    #region TODO
                                    
                                    var resJson = aliApiServ.GetOrderInfo(dr[colOrderID].ToString(), false, false);

                                    var htFirst = JSON.Decode(resJson) as Hashtable;
                                    if (htFirst["success"].ToString().ToLower() == "true")
                                    {
                                        //insStu.ENIDVALUE = enid;
                                        //insStu.RUIDVALUE = ruid;

                                        var arrayList = htFirst["dataList"] as ArrayList;
                                        if (arrayList != null)
                                        {
                                            var ht = new Hashtable();

                                            foreach (Hashtable item in arrayList.Cast<Hashtable>())
                                            {
                                                ht = item;
                                                var insStu = new MODEL.Ali.EditAli_Orders();

                                                #region Init Stu
                                                insStu.ORDERID_VALUE = dr[colOrderID].ToString(); //ht["orderId"];
                                                insStu.BizID_VALUE = ht["bizId"]; 
                                                insStu.ORDERDATE_VALUE = ht["orderDate"];
                                                insStu.ENIDVALUE = ht["snapshotId"];

                                                if (string.IsNullOrEmpty(insStu.ENIDVALUE.ToString()))
                                                {
                                                    //notexistCount++;
                                                    //notexistSb.Append((i + 1) + "、");

                                                    failCount++;
                                                    sbFail.Append("第" + (i + 1) + "行根据订单号：" + dr[colOrderID] + "获取订单信息中snapshotId为空！\r\n");
                                                }

                                                insStu.PRODUCTNAME_VALUE = ht["productName"];
                                                insStu.PRODUCTSKUINFO_VALUE = ht["skuInfo"];
                                                insStu.PRODUCTSNAPSHOTURL_VALUE = ht["productSnapshotUrl"];
                                                insStu.PRODUCTPROPERTIES_VALUE = ht["productProperties"];

                                                if (ht["productProperties"] != null &&
                                                    !string.IsNullOrEmpty(ht["productProperties"].ToString()))
                                                {
                                                    try
                                                    {
                                                        #region Propertites
                                                        var jsonData =
                                                            JSON.Decode(ht["productProperties"].ToString()) as Hashtable;
                                                        insStu.BRANDNAMEVALUE = jsonData["Brand Name"];
                                                        insStu.PRODUCTMODELVALUE = jsonData["Model"];
                                                        if (string.IsNullOrEmpty(insStu.PRODUCTMODELVALUE.ToString()))
                                                        {
                                                            foreach (var key in jsonData.Keys)
                                                            {
                                                                if ((key.ToString().ToLower().EndsWith("model") ||
                                                                     key.ToString().Trim().ToLower() == "model" ||
                                                                     key.ToString().Trim().ToLower() == "model number")
                                                                    && jsonData[key] != null
                                                                    && !string.IsNullOrEmpty(jsonData[key].ToString()))
                                                                {
                                                                    insStu.PRODUCTMODELVALUE = jsonData[key];
                                                                }
                                                            }
                                                        }
                                                        insStu.ITEMCONDITIONVALUE = jsonData["Item Condition"];
                                                        insStu.RAMVALUE = jsonData["RAM"];
                                                        insStu.ROMVALUE = jsonData["ROM"];
                                                        insStu.DISPLAYSIZEVALUE = jsonData["Display Size"];
                                                        insStu.DISPLAYRESOLUTIONVALUE = jsonData["Display Resolution"];
                                                        insStu.BATTERYCAPACITYVALUE = jsonData["Battery Capacity(mAh)"];
                                                        insStu.CPUVALUE = jsonData["CPU"];
                                                        insStu.SIZEVALUE = jsonData["Size"];
                                                        insStu.OPERATIONSYSTEMVALUE = jsonData["Operation System"];
                                                        insStu.OSVALUE = jsonData["OS"];
                                                        #endregion
                                                    }
                                                    catch
                                                    {
                                                    }


                                                }

                                                insStu.STOREURL_VALUE = ht["storeUrl"];

                                                if (dt.Columns.Contains("register_country_id"))
                                                {
                                                    insStu.SELLERCOUNTRY_VALUE = dr["register_country_id"];
                                                }
                                                if (dt.Columns.Contains("register_province_name"))
                                                {
                                                    insStu.SELLERPROVINCE_VALUE = dr["register_province_name"];
                                                }
                                                if (dt.Columns.Contains("full_name"))
                                                {
                                                    insStu.SELLERNAME_VALUE = dr["full_name"];
                                                }
                                                if (dt.Columns.Contains("email"))
                                                {
                                                    insStu.SELLEREMAIL_VALUE = dr["email"];
                                                }
                                                //买家国家
                                                if (ht["country"] != null && !string.IsNullOrEmpty(ht["country"].ToString()))
                                                {
                                                    insStu.COUNTRY_VALUE = ht["country"];
                                                }
                                                else
                                                {
                                                    insStu.COUNTRY_VALUE = dt.Columns.Contains("buyer_country_id")
                                                        ? dr["buyer_country_id"].ToString()
                                                        : string.Empty;
                                                }
                                                //买家省份
                                                if (ht["province"] != null &&
                                                    !string.IsNullOrEmpty(ht["province"].ToString()))
                                                {
                                                    insStu.PROVINCE_VALUE = ht["province"];
                                                }
                                                else
                                                {
                                                    insStu.PROVINCE_VALUE = dt.Columns.Contains("buyer_province")
                                                        ? dr["buyer_province"].ToString()
                                                        : string.Empty;
                                                }
                                                //买家城市
                                                if (ht["city"] != null && !string.IsNullOrEmpty(ht["city"].ToString()))
                                                {
                                                    insStu.CITY_VALUE = ht["city"];
                                                }
                                                else
                                                {
                                                    insStu.CITY_VALUE = dt.Columns.Contains("buyer_city")
                                                        ? dr["buyer_city"].ToString()
                                                        : string.Empty;
                                                }

                                                insStu.STREETADDRESS_VALUE = ht["streetAddress"]; //买家街道
                                                insStu.POSTCODE_VALUE = ht["postCode"]; //买家邮编
                                                insStu.SENDGOODSTIME_VALUE = ht["sendGoodsTime"]; //产品发货时间
                                                insStu.SELLERIDGETGOODSTIME_VALUE = ht["getGoodsTime"]; //产品收货时间
                                                insStu.PRODUCTCOUNT_VALUE = ht["productCount"]; //产品数量
                                                insStu.STATUS_VALUE = ht["status"];
                                                //交易状态。订单状态： 1.PLACE_ORDER_SUCCESS（下单成功）2.WAIT_SELLER_SEND_GOODS（待卖家发货）3.SELLER_PART_SEND_GOODS（待卖家部分发货）4.WAIT_BUYER_ACCEPT_GOODS（等待买家收货）5.FUND_PROCESSING（资金处理中）6.FINISH（交易成功）
                                                insStu.PRODUCTAMOUNT_VALUE = ht["productAmount"]; //产品金额，分
                                                insStu.SERVICEAMOUNT_VALUE = ht["serviceAmount"]; //保修金额，分
                                                insStu.PAYCURRENCY_VALUE = ht["payCurrency"]; //支付币种
                                                insStu.ORDERCURRENCY_VALUE = ht["orderCurrency"]; //订单币种
                                                insStu.EXCHANGE_VALUE = ht["exchange"]; //汇率
                                                insStu.WARRANTYTYPE_VALUE = ht["warrantyType"];
                                                //保修类型. 1.warranty_common（普通保修）2.warranty_refund（只退不修）
                                                insStu.SERVICESTARTTIME_VALUE = ht["serviceStartTime"]; //服务开始时间，买家确认收货之前为空
                                                insStu.SERVICEENDTIME_VALUE = ht["serviceEndTime"]; //服务结束时间，买家确认收货之前为空
                                                insStu.WARRANTYSTATUS_VALUE = ht["warrantyStatus"];
                                                //保修状态 1.notSubmit(未提交)2.create（创建）3.cancel（取消）4.finish（完成）
                                                insStu.NAME_VALUE = ht["name"]; //买家姓名,warrantyStatus=notSubmit时为空
                                                insStu.TELEPHONE_VALUE = ht["telephone"]; //买家电话,warrantyStatus=notSubmit时为空
                                                insStu.DESCRIPTION_VALUE = ht["description"];
                                                //买家保修描述,warrantyStatus=notSubmit时为空
                                                insStu.ATTACHMENTS_VALUE = ht["attachments"];
                                                //买家保修提交附件，逗号分隔,warrantyStatus=notSubmit时为空
                                                #endregion

                                                insStu.ACTION_VALUE = "Insert";
                                                insStu.EFFECTIVE_VALUE = false;

                                                int res = serv.EditAli_Orders(ref insStu);
                                                if (res > 0)
                                                    addSuccessCount++;
                                                else
                                                {
                                                    notexistCount++;
                                                    notexistSb.Append((i + 1) + "、");
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {

                                        notexistCount++;
                                        notexistSb.Append((i + 1) + "、");

                                        failCount++;
                                        sbFail.Append("第" + (i + 1) + "行根据订单号：" + dr[colOrderID] + "获取订单信息失败！\r\n");
                                    }

                                    #endregion

                                    
                                    //不存在，新增
                                    //notexistCount++;
                                    //notexistSb.Append((i + 1) + "、");
                                }
                                else
                                {
                                    //更新 部分字段
                                    for (int j = 0; j < oDt.Rows.Count; j++)
                                    {
                                        try
                                        {
                                            var id = oDt.Rows[j]["ID"].ToString();
                                            var snapshotId = oDt.Rows[j]["ENid"].ToString();
                                            var entity = new MODEL.Ali.EditAli_Orders
                                            {
                                                ACTION_VALUE = "Update",
                                                ID_VALUE = id
                                            };


                                            var resJson = aliApiServ.GetOrderInfo(oDt.Rows[j]["OrderId"].ToString(), false, false);

                                            var htFirst = JSON.Decode(resJson) as Hashtable;
                                            if (htFirst["success"].ToString().ToLower() == "true")
                                            {

                                                var arrayList = htFirst["dataList"] as ArrayList;
                                                if (arrayList != null)
                                                {

                                                    var ht = new Hashtable();
                                                    foreach (
                                                        Hashtable item in
                                                            arrayList.Cast<Hashtable>()
                                                                .Where(
                                                                    item =>
                                                                        item["snapshotId"].ToString() == snapshotId))
                                                    {
                                                        ht = item;
                                                    }
                                                    if (ht.Count <= 0)
                                                    {
                                                        failCount++;
                                                        sbFail.Append("第" + (i + 1) + "行调用Ali接口数据中没有Order=" +
                                                                      oDt.Rows[j]["OrderId"].ToString() + ";snapshotId=" +
                                                                      snapshotId + ";\r\n");
                                                        continue;
                                                    }
                                                    entity.BizID_VALUE = ht["bizId"]; 
                                                    //买家国家
                                                    if (ht["country"] != null &&
                                                        !string.IsNullOrEmpty(ht["country"].ToString()))
                                                    {
                                                        entity.COUNTRY_VALUE = ht["country"];
                                                    }
                                                    //买家省份
                                                    if (ht["province"] != null &&
                                                        !string.IsNullOrEmpty(ht["province"].ToString()))
                                                    {
                                                        entity.PROVINCE_VALUE = ht["province"];
                                                    }
                                                    //买家城市
                                                    if (ht["city"] != null &&
                                                        !string.IsNullOrEmpty(ht["city"].ToString()))
                                                    {
                                                        entity.CITY_VALUE = ht["city"];
                                                    }

                                                    entity.STREETADDRESS_VALUE = ht["streetAddress"]; //买家街道
                                                    entity.POSTCODE_VALUE = ht["postCode"]; //买家邮编
                                                    entity.SENDGOODSTIME_VALUE = ht["sendGoodsTime"]; //产品发货时间
                                                    entity.SELLERIDGETGOODSTIME_VALUE = ht["getGoodsTime"]; //产品收货时间
                                                    //entity.PRODUCTCOUNT_VALUE = ht["productCount"]; //产品数量
                                                    entity.STATUS_VALUE = ht["status"];
                                                    //交易状态。订单状态： 1.PLACE_ORDER_SUCCESS（下单成功）2.WAIT_SELLER_SEND_GOODS（待卖家发货）3.SELLER_PART_SEND_GOODS（待卖家部分发货）4.WAIT_BUYER_ACCEPT_GOODS（等待买家收货）5.FUND_PROCESSING（资金处理中）6.FINISH（交易成功）
                                                    entity.WARRANTYTYPE_VALUE = ht["warrantyType"];
                                                    //保修类型. 1.warranty_common（普通保修）2.warranty_refund（只退不修）
                                                    entity.SERVICESTARTTIME_VALUE = ht["serviceStartTime"];
                                                    //服务开始时间，买家确认收货之前为空
                                                    entity.SERVICEENDTIME_VALUE = ht["serviceEndTime"];
                                                    //服务结束时间，买家确认收货之前为空
                                                    entity.WARRANTYSTATUS_VALUE = ht["warrantyStatus"];
                                                    //保修状态 1.notSubmit(未提交)2.create（创建）3.cancel（取消）4.finish（完成）
                                                    entity.NAME_VALUE = ht["name"]; //买家姓名,warrantyStatus=notSubmit时为空
                                                    entity.TELEPHONE_VALUE = ht["telephone"];
                                                    //买家电话,warrantyStatus=notSubmit时为空
                                                    entity.DESCRIPTION_VALUE = ht["description"];
                                                    //买家保修描述,warrantyStatus=notSubmit时为空
                                                    entity.ATTACHMENTS_VALUE = ht["attachments"];
                                                    //买家保修提交附件，逗号分隔,warrantyStatus=notSubmit时为空
                                                }

                                                serv.EditAli_Orders(ref entity);
                                                succCount++;
                                            }
                                            else
                                            {
                                                failCount++;
                                                sbFail.Append("第" + (i + 1) + "行调用Ali接口失败;\r\n");
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            failCount++;
                                            sbFail.Append("第" + (i + 1) + "行异常：" + ex.Message);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                failCount++;
                                sbFail.Append("第" + (i + 1) + "行异常！" + ex.Message + "\r\n");
                            }
                        }

                        //ShowAlert();

                        txtInfo.Text = string.Format("新增数量:{0}！\r\n更新成功数量：{1}！\r\n更新失败数量：{2}\r\n{3}\r\n{4}\r\n{5}",addSuccessCount, succCount,
                            failCount,
                            notexistCount != 0 ? "不存在数量:" + notexistCount + "" : string.Empty,
                            string.IsNullOrEmpty(notexistSb.ToString())
                                ? string.Empty
                                : "第" + notexistSb.ToString().Trim('、') + "行数据不存在",
                            string.IsNullOrEmpty(sbFail.ToString()) ? string.Empty : sbFail.ToString());
                    }
                    else
                    {
                        ShowAlert("请选择正确的文件类型！");
                    }
                }
                catch (Exception ex)
                {
                    ShowAlert(ex.Message);
                }
            }
            else
            {
                ShowAlert("请选择文件！");
            }
        }
    }
}